cc.Class({
    extends: cc.Component,

    properties: {
        // HistoryItemPrefab:{
        //     default:null,
        //     type:cc.Prefab
        // },
        numAtlas:{
            default:null,
            type:cc.SpriteAtlas
        },
        paiAtlas:{
            default:null,
            type:cc.SpriteAtlas
        },
        // foo: {
        //    default: null,
        //    url: cc.Texture2D,  // optional, default is typeof default
        //    serializable: true, // optional, default is true
        //    visible: true,      // optional, default is true
        //    displayName: 'Foo', // optional
        //    readonly: false,    // optional, default is false
        // },
        // ...
        _history:null,

        _viewlist:null,
         _content:null,
        _viewitemTemp:null,

        _viewlistGame:null,
        _contentGame:null,
        _viewitemGame:null,

        _historyData:null,
        _curRoomInfo:null,
        _emptyTip:null
    },

    // use this for initialization
    onLoad: function () {
        cc.vv.history=this;
        this._history = this.node.getChildByName("history");
        this._history.active = false;
        // 无战绩时的显示
        this._emptyTip = this._history.getChildByName("emptyTip");
        this._emptyTip.active = true;
        // 房间列表显示
        this._viewlist = this._history.getChildByName("viewlist");
        this._content = cc.find("view/content",this._viewlist);
        this._viewitemTemp = this._content.children[0];
        this._content.removeAllChildren()
        // 每一局显示列表
        this._viewlistGame = this._history.getChildByName("viewlistGame");
        this._contentGame = cc.find("view/content",this._viewlistGame);
        this._viewitemGame = this._contentGame.children[0];
        this._viewitemGame.removeFromParent()

        var node = cc.find("Canvas/btn_zhanji");        
        this.addClickEvent(node,this.node,"History","onBtnHistoryClicked");
        
        var node = cc.find("Canvas/history/btn_back");  
        this.addClickEvent(node,this.node,"History","onBtnBackClicked")
    },
    
    addClickEvent:function(node,target,component,handler){
        var eventHandler = new cc.Component.EventHandler();
        eventHandler.target = target;
        eventHandler.component = component;
        eventHandler.handler = handler;

        var clickEvents = node.getComponent(cc.Button).clickEvents;
        clickEvents.push(eventHandler)
    },
    
    onBtnBackClicked:function(){
        if(this._curRoomInfo == null){
            this._historyData = null;
            this._history.active = false
        }else{
            this.initRoomHistoryList(this._historyData)
        }
    },
    
    onBtnHistoryClicked:function(){
        console.log("onBtnHistoryClicked");
        cc.vv.audioMgr.playSFX("select.mp3");
        this._history.active = true;
        var self = this;
        cc.vv.userMgr.getHistoryList(function(data){
            data.sort(function(a,b){
                return a.time < b.time
            });
            console.log("data",data);
            self._historyData = data;
            self.initRoomHistoryList(data)
        });
    },
    
    dateFormat:function(time,isShortTime){
        var date = new Date(time);
        var datetime = "{0}-{1}-{2} {3}:{4}:{5}";
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        month = month >= 10? month : ("0"+month);
        var day = date.getDate();
        day = day >= 10? day : ("0"+day);
        var h = date.getHours();
        h = h >= 10? h : ("0"+h);
        var m = date.getMinutes();
        m = m >= 10? m : ("0"+m);
        var s = date.getSeconds();
        s = s >= 10? s : ("0"+s);
        if (isShortTime) {
            datetime = h+":"+m;
        }else{
            datetime = datetime.format(year,month,day,h,m,s);
        };
        // console.log("返回格式化datetime",datetime);
        return datetime
    },
    
    initRoomHistoryList:function(data){
        console.log("initRoomHistoryList",data);
        this._emptyTip.active = data.length == 0;
        this._viewlist.active=true;
        this._viewlistGame.active=false;
        data.sort(function(a,b){
           return b.time - a.time
        });
        for(var i = 0; i < data.length; ++i){
            var node = this.getViewItem(i,"room");
            node.idx = i;
            // 房号、时间、房主（第一个坐席）
            node.getChildByName("roomNo").getComponent(cc.Label).string = data[i].id;
            var datetime = this.dateFormat(data[i].time * 1000);
            node.getChildByName("time").getComponent(cc.Label).string = datetime;
            node.getChildByName("fangzhuName").getComponent(cc.Label).string = data[i].seats[0].name;
            var btnOp = node.getChildByName("btnOp");
            btnOp.active=true;
            btnOp.idx = i;
            
            for(var j = 0; j < 4; ++j){
                var item=node.getChildByName("item"+j);
                item.active=false;
                var s = data[i].seats[j];
                var info="";
                var fen="";
                if (s) {
                    info = s.name;
                    fen = s.score;
                    item.active=true
                };
                // console.log(info);
                item.getChildByName("info").getComponent(cc.Label).string = info;
                // 分数改成图片
                var scoreNode=item.getChildByName("score");
                this.setNumSprite(fen,scoreNode)
            }
        };
        this.shrinkContent(data.length);
        this._curRoomInfo = null
    },
    
    initGameHistoryList:function(roomInfo,data){
        this._viewlistGame.active=true;
        this._viewlist.active=false;
        data.sort(function(a,b){
           return b.create_time - a.create_time
        });
        console.log("initGameHistoryList",roomInfo,data);
        // 房号显示
        this._viewlistGame.getChildByName("roomNo").getComponent(cc.Label).string="房号:"+roomInfo.id;
        // 玩家姓名
        var cont=this._viewlistGame.getChildByName("cont");
        for (var i = 0; i < 4; i++) {
            cont.getChildByName("name"+i).getComponent(cc.Label).string=roomInfo.seats[i].name  
        };
        // 游戏信息
        for(var i = 0; i < data.length; ++i){
            var node = this.getViewItem(i,"game");
            var titleId = data.length - i ;
            
            node.getChildByName("num").getComponent(cc.Label).string = titleId;
            var datetime = this.dateFormat(data[i].create_time * 1000,true);
            node.getChildByName("time").getComponent(cc.Label).string = datetime;
           
            var result = JSON.parse(data[i].result);
    
            for(var j = 0; j < result.length; ++j){
                var item=node.getChildByName("item"+j);
                // 先隐藏，有坐席再显示
                item.active=false;
                if (roomInfo.seats) {
                    item.active=true
                };
                var pais=result[j].peipaione.concat(result[j].peipaitwo);
                // 分数（图片显示）
                var scoreArr=(result[j].score+"").split("");
                var scoreNode=item.getChildByName("score");
                this.setNumSprite(result[j].score,scoreNode)
                // 牌显示（图片）
                var paiNode=item.getChildByName("pai");
                for (var k = 0; k < paiNode.childrenCount; k++) {
                    if (pais[k]) {
                        paiNode.children[k].getComponent(cc.Sprite).spriteFrame=this.paiAtlas.getSpriteFrame(pais[k])
                    }else{
                        paiNode.children[k].getComponent(cc.Sprite).spriteFrame=null
                    }
                };
                // 叫分显示
                if (result[j].scoreone==-1) {
                    item.getChildByName("toutao").active=false;
                    item.getChildByName("toutaoS").active=false;
                    item.getChildByName("ertao").active=false;
                    item.getChildByName("ertaoS").active=false;
                }else{
                    var toutao=item.getChildByName("toutao");
                    toutao.active=true;
                    var ertao=item.getChildByName("ertao");
                    ertao.active=true;
                    item.getChildByName("toutaoS").active=true;
                    item.getChildByName("ertaoS").active=true;
                    toutao.getComponent(cc.Label).string=result[j].scoreone;
                    ertao.getComponent(cc.Label).string=result[j].scoretwo
                };
                
                // 庄显示
                item.getChildByName("zhuang").active=result[j].zhuang
            }
        };
        this.shrinkContent(data.length);
        this._curRoomInfo = roomInfo
    },
    
    getViewItem:function(index,contName){
        if (contName=="room") {
            var content = this._content;
            if(content.childrenCount > index){
                return content.children[index]
            };
            var node = cc.instantiate(this._viewitemTemp);
            content.addChild(node);
            return node
        }else{
            var content = this._contentGame;
            if(content.childrenCount > index){
                return content.children[index]
            };
            var node = cc.instantiate(this._viewitemGame);
            content.addChild(node);
            return node
        }
    },
    shrinkContent:function(num){
        while(this._content.childrenCount > num){
            var lastOne = this._content.children[this._content.childrenCount -1];
            this._content.removeChild(lastOne,true)
        };
        while(this._contentGame.childrenCount > num){
            var lastOne = this._contentGame.children[this._contentGame.childrenCount-1];
            this._contentGame.removeChild(lastOne,true)
        };
    },
    
    getGameListOfRoom:function(idx){
        var self = this;
        var roomInfo = this._historyData[idx];        
        cc.vv.userMgr.getGamesOfRoom(roomInfo.uuid,function(data){
            if(data != null && data.length > 0){
                self.initGameHistoryList(roomInfo,data)
            }
        })
    },
    
    getDetailOfGame:function(idx){
        var self = this;
        var roomUUID = this._curRoomInfo.uuid;
        cc.vv.userMgr.getDetailOfGame(roomUUID,idx,function(data){
            data.base_info = JSON.parse(data.base_info);
            data.action_records = JSON.parse(data.action_records);
            cc.vv.gameNetMgr.prepareReplay(self._curRoomInfo,data);
            cc.vv.replayMgr.init(data);
            cc.director.loadScene("mjgame")
        })
    },
    
    onViewItemClicked:function(event){
        var idx = event.target.idx;
        console.log("onViewItemClicked",idx);
        if(this._curRoomInfo == null){
            this.getGameListOfRoom(idx)
        }else{
            // 纸牌类没有回放
            if (event.target.hasReplay==false) {return};
            this.getDetailOfGame(idx)
        }
    },
    
    onBtnOpClicked:function(event){
        var idx = event.target.parent.idx;
        // console.log(idx);
        if(this._curRoomInfo == null){
            this.getGameListOfRoom(idx)
        }else{
            this.getDetailOfGame(idx)     
        }
    },
    getNumSpriteFrameByNum:function(num){
        return this.numAtlas.getSpriteFrame(num)   
    },
    setNumSprite:function(fen,target){
        target.removeAllChildren();
        var scoreArr=(fen+"").split("");
        // console.log("scoreArr",scoreArr);
        if (fen>0) {
            var spriteNode=new cc.Node("New Sprite");
            var sprite = spriteNode.addComponent(cc.Sprite);
            sprite.spriteFrame=this.getNumSpriteFrameByNum("+");
            target.addChild(spriteNode)
        }else if (fen<0) {
            var spriteNode=new cc.Node("New Sprite");
            var sprite = spriteNode.addComponent(cc.Sprite);
            sprite.spriteFrame=this.getNumSpriteFrameByNum("-");
            scoreArr.splice(0,1);
            target.addChild(spriteNode)
        };
        // 具体分数
        for (var q = 0; q < scoreArr.length; q++) {
            var  name="";
            if (fen>0) {
                name="0"+scoreArr[q]
            }else{
                name=scoreArr[q]
            };
            var spriteNode=new cc.Node("New Sprite");
            var sprite = spriteNode.addComponent(cc.Sprite);
            sprite.spriteFrame=this.getNumSpriteFrameByNum(name);
            target.addChild(spriteNode)
        }
    }
    // called every frame, uncomment this function to activate update callback
    // update: function (dt) {

    // },
});
